package top.someapp.base;

import android.os.Bundle;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import java.lang.reflect.Field;
import top.someapp.annotation.BindView;

/**
 * @author zwz
 * Created on 2021-07-18
 */
public abstract class BaseFragmentActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentViewId());
        bindView();
        initView();
        addListeners();
    }

    protected abstract @LayoutRes int getContentViewId();

    public abstract @IdRes int getFragmentContainerId();

    public void replaceFragment(@NonNull Fragment fragment) {
        final int fragmentContainerId = getFragmentContainerId();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
            .replace(fragmentContainerId, fragment)
            .commit();
    }

    protected void initView() {}

    protected void addListeners() {}

    private void bindView() {
        Field[] fields = getClass().getDeclaredFields();
        if (fields.length < 1) return;
        for (Field field : fields) {
            try {
                if (field.isAnnotationPresent(BindView.class)) {
                    BindView annotation = field.getAnnotation(BindView.class);
                    int id = annotation.value();
                    if (id > 0) {
                        field.set(this, findViewById(id));
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}
